<?php 
/*****************
* 任务发布
*创建日期:2012-8-24
*作者：tjx
******************/

define('IN_WONDERSHARE', true);
header("Content-type:text/html;charset=utf-8");
ob_start("ob_gzhandler");
require('../includes/init.php');
require ('./configs/site_config.php');

class TaskPub {
	
	private  $db;
	private $type;//操作类型
	/**
	* @ 构造函数
	* @ __construct
	*/
	
	public function __construct() {
		
		$this->db = $GLOBALS['db'];
		
		$type_array = array('self', 'admin', 'pub');//任务类型
		
		$this->type = trim($_REQUEST['type']);
		if ( !in_array($this->type, $type_array) ) {
			echo "任务类型错误。";
			exit;
		}
	}


	/**
	* 发布任务
	* @return  array
	*/
	public function pub() {
		if ( empty($_SESSION['AEmail']) ) {
			mainAlert("你的邮箱为空不能发布，请找本站的管理员为你加上邮箱！", $_SERVER['HTTP_REFERER']);	
			exit;
		}
		
		$mId_str =  trim($_GET['mId_str']);
		if ( empty($mId_str) ) {
			mainAlert("你没有选择任何任务发布！", $_SERVER['HTTP_REFERER']);
			exit;
		}
		
		$where_str = '';
		if ( $this->type == 'self' ) {//如果发布者为自己
			$where_str = " AND m.mCreatAid = {$_SESSION['AID']} ";
		} elseif ($this->type == 'pub') {
			$where_str = " AND m.mPubAid = {$_SESSION['AID']} ";
		}
		
		$sql = "SELECT 
				m.mId,
				m.sId,	
				m.mEditFile,
				m.mDeleteFile,
				m.mCdnEditFile,
				m.mCdnDeleteFile,
				m.mMsgFile,
				s.sIsCdn,
				s.sSer_Id,
				s.sDirPath
				FROM task_manage m, task_site s
				WHERE FIND_IN_SET(m.mId, '{$mId_str}')  {$where_str}  AND m.sId = s.sId";
		$sql = "{$sql} AND m.mState = 4 AND m.mIsDelete = 0
				UNION ALL 
				{$sql}  AND m.mState = 3 AND m.mIsDelete = 0";
		$result = $this->db->query($sql);
		
		$cdnuser = 'cdn_account2@wondershare.cn' ;
		$cdnpwd = 'cdn2_password' ;
		$url = "http://cms.wondershare.com.wx/cgi-bin/pub.cgi?" ;

		while ($row = $this->db->fetch_array($result, MYSQL_ASSOC)) {

			$dir = substr($row['mEditFile'] , 0, strrpos($row['mEditFile'], "/"));
						
			$domain_arr = explode('/', $row['sDirPath'] ) ; 
			$domain = $domain_arr[4] ;
			
			$is_cdn = $row['sIsCdn'] == 1 ? true : false ;
		
			$url = $url.'dir='.$dir.'&cdnuser='.$cdnuser.'&cdnpwd='.$cdnpwd.'&email='.$_SESSION['AEmail'].'&domain='.$domain.'&is_cdn='.$is_cdn ;
			$rs = file_get_contents($url);
			echo "rs:<br>{$rs}<br>{$url}<hr />";
		}
		
		mainAlert('正在发布中...\n如果查看发布进度请到发布相关任务的  "发布时信息日记文件"  去查看 .', $_SERVER['HTTP_REFERER']);
		
		
	}
	
	/**
	* 发布cms文件到外网
	* @param   string   cms_file  要发送的文件
	* @param   string   $mMsgFile  记录发送过程中的消息文件
	* @param   string   $serIp  发送至那个服务器IP
	* @return  array
	*/
	function pubCmsFile($cms_file, $mMsgFile, $serIp, $type) {
		
		$sum = 1;//用于计数
		$msg = "{$cms_file} <span style='color:#F00; font-size:18px'>文件为空！</span>";
		$file_contents = file_get_contents($cms_file);
	
		if ( !empty( $file_contents ) ) {
			
			$sh_file_name = '';
			
			if ( $type == 'del' ) {
				$sh_file_name = 'rsync_del.sh';
			} elseif ( $type == 'edit' ) {
				$sh_file_name = 'rsync.sh';
				
			}
			
		
			if ( !empty($sh_file_name) ) {
				exec("/usr/local/worksh/{$sh_file_name} {$cms_file} {$serIp} 1>> {$mMsgFile}", $out, $int);	
				
				if ( $int != 0 ) {
					
					foreach($out as $a){
					  $msg .= $a."<br>";
					} 
					if ( empty($msg) ) {
						$msg = '未知错误，请与管理员联系。';
					}
					$sum = 0;
					
				} else {
					$msg = "<span style='color:#F00; font-size:18px'>成功！</span>";
				}
				
			}
		}
		
		return array('msg' => $msg, 'sum' => $sum);
	}
	
	/**
	* 判断cnd最大行数并生成相应的临时文件
	* @param   string    $file_name   文件名称(全路径)
	* @param   string     $type   类型
	* @return  
	*/
	
	function isCndFileMaxLine($file_name, $type = 'edit') {
		
		$msg = "{$file_name} <span style='color:#F00; font-size:18px'>文件为空或不存在！</span>||";
		$is_success = 1;
		$file_contents = file_get_contents($file_name);
		
		if ( file_exists($file_name) && !empty( $file_contents) ) {

			$file_path = dirname($file_name);//文件所在路径
			$url_str = '';//定义临时url字符串
			$url_array = file($file_name);//获取文件url数组
			
			$nums = 0;//产生临时文件个数
			
			$max_sum = count($url_array);//获取文件最大行数
			if ($max_sum >= 50 ) {
				foreach ($url_array AS $key => $value) {
				
					$url_str .= $value;
					if (($key + 1) % 50  == 0 ) {
						
						file_put_contents("{$file_path}/tem_{$type}_urls_{$nums}.txt", $url_str);
						$nums += 1;
						$url_str = '';
					}
					
					if ($max_sum == ($key + 1))  {
						file_put_contents("{$file_path}/tem_{$type}_urls_{$nums}.txt", $url_str);
						$nums += 1;
					}
				}
			}
		
			if ($nums == 0 ) {
				
				$info_array = $this->pubCdnFile($file_name, $type);
				echo 'info_array'.'<pre>'.print_r($info_array , true ).'</pre>'; 	// pkjueying
				$runtime = $info_array['runtime'] / 60;
				$msg = $runtime > 0 ? 
									"cnd同步成功，需要时间：<span style='color:#F00; font-size:18px'>{$runtime}</span> 分才能保证全球同步成功。||
									本次操作的SessionID:<span style='color:#F00; font-size:18px'><{$info_array['sessionID']}></span>(通知邮件ID)||" 
									: 
									"cnd同步错误，错误信息：{$info_array['errmsg']}||";   //cnd同步错误，错误信息：An internal error has occurred. Please contact customer support and provide them with the session id.
				$is_success = $info_array['sum'];//是否成功标志
				
			} else {
				 $sum = 0;
				for ($i = 0 ; $i < $nums; $i++) {
					
					$file_name = "{$file_path}/tem_{$type}_urls_{$i}.txt";
					$info_array = $this->pubCdnFile($file_name, $type);
					$runtime = $info_array['runtime'] / 60;
					$sum += $info_array['sum'];
					
					$msg .= $runtime > 0 ?   
										"第<span style='color:#F00; font-size:18px'>".($i + 1)."</span>个缓存文件cnd同步成功，需要时间：
										<span style='color:#F00; font-size:18px'>{$runtime}</span> 分才能保证全球同步成功。||
										本次操作的SessionID:<span style='color:#F00; font-size:18px'><{$info_array['sessionID']}></span>(通知邮件ID)||" 
										: 
										"第<span style='color:#F00; font-size:18px'>".($i + 1)."</span>个缓存文件cnd同步错误，错误信息：{$info_array['errmsg']}||";
					unlink($file_name);
				}
				$is_success = $sum == $nums ? 1 : 0;//是否成功标志
			}
			$msg = $msg;
			
		}
		
		return array('msg' => $msg, 'is_success' => $is_success);

	}
	
	/**
	* 发布cnd文件
	*
	* @param   string      $file_name      cdn要发布的文件
	* @param   string      $type           发布类型
	* @return  int
	*/
	
	function pubCdnFile($file_name, $type ) {
		echo 'file_name == ' . $file_name . '---------- type ==' .$type ;	//pkjueying
		$runtime = 0;
		$sum = 0;//用于计数
		$errmsg = '';
		$sessionID = '';
		
		if ( !empty($file_name) ) {
			
			$action = '';
			if ($type == 'edit') {
				$action = 'invalidate'; //更新动作
				
			} elseif ($type == 'del') {
				$action = 'remove'; //删除动作
				
			}
			
			if ( empty($action) ) {
				echo '发布类型错误';
				exit;
			}
				
			///// pkjueying
			$result = exec("/usr/local/worksh/CCURequest.pl --user admin@wondershare.com --pwd YYtuANCedeq1 --file {$file_name} --domain production --email {$_SESSION['AEmail']} --action {$action}", $output, $int_tag);
			echo 'exec---'."/usr/local/worksh/CCURequest.pl --user admin@wondershare.com --pwd YYtuANCedeq1 --file {$file_name} --domain production --email {$_SESSION['AEmail']} --action {$action}", $output, $int_tag;
			echo 'result-----------'.'<pre>'.print_r($output , true ).'</pre>';
			//$output = exec("/usr/local/worksh/CCURequest.pl --user admin@wondershare.com --pwd YYtuANCedeq1 --file {$file_name} --domain production --email {$_SESSION['AEmail']} --action {$action}", $output, $int_tag);
			if ( !empty($output) ) {
				echo 'output'.'<pre>'.print_r($output , true ).'</pre>';
				foreach ($output AS $key => $value) {
					
					if (substr_count($value, 'estTime:') > 0) {
						$runtime = (int) str_replace('estTime:', '', $value);
					} elseif (substr_count($value, 'resultMsg:') > 0) {
						$errmsg = trim(str_replace('resultMsg:', '', $value));
					} elseif (substr_count($value, 'sessionID:') > 0) {
						$sessionID = trim(str_replace('sessionID:', '', $value));
					}
					
				
				}
			}
			
			if ($int_tag == 0) {
				$sum = 1;
			}
		}
		
		return array('runtime' => $runtime, 'errmsg' => $errmsg, 'sum' => $sum, 'sessionID' => $sessionID);
	}
	
	/**
	* 根据站点对应服务器ID获取相应的服务器IP( 可以有多个服务器IP，以逗号隔开)
	* @param   int      $sSer_Id       队列主键
	* @return  array
	*/
	public function getSiteServerIp($sSer_Id) {
		
		$serIp = '';
		if ( !empty($sSer_Id) ) {
			$sql = "SELECT serIp 
					FROM task_server 
					WHERE FIND_IN_SET(serId, '{$sSer_Id}')";
			$rows = $this->db->getAll($sql);
			
			$str = '';
			foreach ($rows AS $key => $value) {
				$serIp .= $str.long2ip($value['serIp']);
				$str = ',';
			}
		
		}
		return $serIp;
	}
	
	

}

$action    = $_REQUEST['action']; 
$task_pub   = new TaskPub;
if ( method_exists($task_pub, $action) )  {
	$task_pub->$action();
} else {
	$task_pub->index();
}

?>
